﻿//#if UNITY_5_3_OR_NEWER

using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
//using UnityEditor.SceneManagement;
using Newtonsoft.Json;



public class IsoAppInfo
{
    public string team_id;
    public string username;
    public string password;
}

public static class VersionTool
{
    public static string BuildTargetGroupToAppInfoKey(BuildTargetGroup g)
    {
        switch(g)
        {
            case BuildTargetGroup.iOS:
                return BuildTarget.iOS.ToString().ToLower();
            default:
                return g.ToString().ToLower();
        }
    }

    [MenuItem("Custom/Version/SetSdkConfig")]
    public static void SetSdkConfig ()
    {
        string androidSdkPath = System.Environment.GetEnvironmentVariable("ANDROID_SDK_HOME", System.EnvironmentVariableTarget.Process);
        string androidNdkPath = System.Environment.GetEnvironmentVariable("ANDROID_NDK_HOME", System.EnvironmentVariableTarget.Process);

        EditorPrefs.SetString("AndroidSdkRoot", androidSdkPath);
        EditorPrefs.SetString("AndroidNdkRootR16b", androidNdkPath);
        EditorPrefs.SetString("AndroidNdkRoot", androidNdkPath);
    }

    [MenuItem("Custom/Version/SetIcon")]
    public static void SetIcon ()
    {
        BuildTargetGroup[] targets = new BuildTargetGroup[]{ BuildTargetGroup.Unknown };
        for (int j = 0; j < targets.Length; j++)
        {
            Texture2D[] icons = PlayerSettings.GetIconsForTargetGroup(targets[j]);
            for (int i = 0; i < icons.Length; i++)
            {
                string iconPath = AssetDatabase.GetAssetPath(icons[i]);
                int index = iconPath.LastIndexOf('_');
                iconPath = iconPath.Substring(0, index + 1) + VersionEx.compile_type + System.IO.Path.GetExtension(iconPath);
                icons[i] = AssetDatabase.LoadAssetAtPath<Texture2D>(iconPath);
            }

            PlayerSettings.SetIconsForTargetGroup(targets[j], icons);
        }

        AssetDatabase.SaveAssets();
    }

	[MenuItem("Custom/Version/SetAppName")]
    public static void SetAppName ()
    {
		PlayerSettings.productName = CommonUtil.GetAppInfo().app_name;
        AssetDatabase.SaveAssets();
    }



	[MenuItem("Custom/Version/SetVersion")]
	public static void SetVersion ()
	{
        if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS)
        {
            TextAsset IsoAppInfoStr = AssetDatabase.LoadAssetAtPath<TextAsset>("Assets/editor_config/ios_app_info.txt");
            IsoAppInfo iosAppInfo = JsonConvert.DeserializeObject<IsoAppInfo>(IsoAppInfoStr.text);
            PlayerSettings.iOS.appleDeveloperTeamID = iosAppInfo.team_id;
        }

        TextAsset appInfoStr = AssetDatabase.LoadAssetAtPath<TextAsset>(ResourcesEx.ResDir + "/app_info.txt");
        AppInfo appInfo = JsonConvert.DeserializeObject<AppInfo>(appInfoStr.text);

        BuildTargetGroup[] groups = new BuildTargetGroup[]{ BuildTargetGroup.Android, BuildTargetGroup.iOS };
        for (int i = 0; i < groups.Length; i++)
        {
            BuildTargetGroup group = groups[i];
            string groupStr = BuildTargetGroupToAppInfoKey(group);
			string package_name_prefix = appInfo.GetPackageNamePrefix(groupStr);
			// Dictionary<string, string> packageInfo = appInfo.platform_info[groupStr].third_party_info[VersionEx.compile_type.ToString()];
            string bundleName = package_name_prefix + VersionEx.compile_type;
            PlayerSettings.SetApplicationIdentifier(group, bundleName);
        }

        PlayerSettings.bundleVersion = VersionEx.version;
        PlayerSettings.Android.bundleVersionCode = VersionEx.version_number;
        PlayerSettings.iOS.buildNumber = VersionEx.version_number + "";

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

//		if(EditorUserBuildSettings.activeBuildTarget == EditorCommonTool.build_target_ios)
//		{
//            PlayerSettings.iOS.buildNumber = Version.version_number.ToString();
//			PlayerSettings.bundleVersion += "-" + Application.unityVersion;
//
//			if(SwitchConfig.compileType == CompileType.release)
//			{
//				
//			}
//			else
//			{
//				PlayerSettings.bundleVersion += "-" + Application.unityVersion;
//			}
//		}
//		else if(EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android)
//		{
//			PlayerSettings.SetPropertyInt("ScriptingBackend", (int)ScriptingImplementation.IL2CPP,BuildTarget.Android);
//
//			if(SwitchConfig.compileType == CompileType.release)
//			{
//				PlayerSettings.Android.bundleVersionCode = Version.build_version;
//			}
//			else
//			{
////				PlayerSettings.bundleVersion += "-" + Application.unityVersion;
////				PlayerSettings.bundleVersion += "-" + (ScriptingImplementation)PlayerSettings.GetPropertyInt("ScriptingBackend", BuildTargetGroup.Android);
//			}
////
////			PlayerSettings.SetPropertyInt(BuildTargetGroup.Android, ScriptingImplementation.IL2CPP);
//		}

//		if(EditorCommonTool.getPlatform() != Platform.ios)
//		{
			//			string bundleIdentifier = "com.topgamesinc.evony" + SwitchConfig.compileType;
			//			switch(SwitchConfig.compileType)
			//			{
			////				case CompileType.alpha:
			////				{
			////					bundleIdentifier = "com.topgames.evonyalpha";
			////				}
			////				break;
			//	
			//				case CompileType.release:
			//				{
			//					bundleIdentifier = "com.topgamesinc.evonyrc";
			//				}
			//				break;
			//			}

			//			PlayerSettings.bundleIdentifier = bundleIdentifier;
			//			PlayerSettings.iPhoneBundleIdentifier = bundleIdentifier;

//			string productName = "Evony";
//			//		if(SwitchConfig.compileType != CompileType.release)
//			{
//				PlayerSettings.productName = productName + "_" + SwitchConfig.compileType;
//			}
			//		else
			//		{
			//			PlayerSettings.productName = "Evony(Beta)";
			//		}
//		}




		//		string filePath = "ProjectSettings/ProjectSettings.asset";
		//		string str = CommonUtil.fileToString(filePath);
		//		switch(EditorUserBuildSettings.activeBuildTarget)
		//		{
		//			case EditorCommonTool.build_target_ios:
		//			{
		//			str = Regex.Replace(str, "(\\s+iPhoneShortBundleVersion:\\s*)(.*)", "${1}" + Version.version);
		//			str = Regex.Replace(str, "(\\s+iPhoneBundleVersion:\\s*)(.*)", "${1}" + Version.build_version);
		//				//no use
		//			str = Regex.Replace(str, "(\\s+AndroidBundleVersionCode:\\s*)(.*)", "${1}" + Version.build_version);
		//			}
		//			break;
		//
		//			case BuildTarget.Android:
		//			{
		//				str = Regex.Replace(str, "(\\s+iPhoneBundleVersion:\\s*)(.*)", "${1}" + Version.version);
		//				str = Regex.Replace(str, "(\\s+AndroidBundleVersionCode:\\s*)(.*)", "${1}" + Version.build_version);
		//				//no use
		//				str = Regex.Replace(str, "(\\s+iPhoneShortBundleVersion:\\s*)(.*)", "${1}" + Version.build_version);
		//			}
		//			break;
		//		}
		//
		//		bool ret = CommonUtil.stringToFile(str, filePath);
		//		if(!ret)
		//		{
		//			Debug.LogError("fileToString Failed: " + filePath);
		//		}
	}

//	[MenuItem("Custom/OldProject/Version/TestVersion")]
//	public static void TestVersion()
//	{
//		string bundleVersion = PlayerSettings.bundleVersion;
//		string shortBundleVersion = PlayerSettings.iOS.buildNumber;
//		int versionCode = PlayerSettings.Android.bundleVersionCode;
//
//		Debug.Log(bundleVersion + " | " + shortBundleVersion + " | " + versionCode);
//		Debug.Log(PlayerSettings.bundleIdentifier + " | " + PlayerSettings.iPhoneBundleIdentifier);
//	}

	//
	//	[MenuItem("Custom/OldProject/Version/SwitchConfigAlpha")]
	//	public static void SwitchConfigAlpha()
	//	{
	//		SetSwitchConfig(CompileType.alpha);
	//	}
	//
	//	public static string replaceParam(string str, string paramName, string paramValue)
	//	{
	//		str = Regex.Replace(str, "(\\s+" + paramName + "\\s*=\\s*)(.*)", "${1}" + paramValue + ";");
	//		return str;
	//	}
	//
	//	public static void SetSwitchConfig(CompileType type)
	//	{
	//		string filePath = "Assets/Scripts/SwitchConfig.cs";
	//		string str = CommonUtil.fileToString(filePath);
	//
	//		{
	//			string paramName = "compileType";
	//			string paramValue = "CompileType." + type.ToString();
	//			str = replaceParam(str, paramName, paramValue);
	//		}
	//		bool ret = CommonUtil.stringToFile(str, filePath);
	//		if(!ret)
	//		{
	//			Debug.LogError("fileToString Failed: " + filePath);
	//		}
	//	}
}
//#else
//
//using UnityEngine;
//using UnityEditor;
//using System.IO;
//using System.Text.RegularExpressions;
//
//public static class VersionTool
//{
//	[MenuItem("Custom/OldProject/Version/SetVersion")]
//	public static void SetVersion ()
//	{
//		if(EditorUserBuildSettings.activeBuildTarget == EditorCommonTool.build_target_ios)
//		{
//			PlayerSettings.shortBundleVersion = VersionEx.version;
//			PlayerSettings.bundleVersion = VersionEx.version_number.ToString();
//		}
//		else if(EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android)
//		{
//			PlayerSettings.bundleVersion = VersionEx.version;
//			if(SwitchConfig.compileType == CompileType.release)
//			{
//				PlayerSettings.Android.bundleVersionCode = VersionEx.version_number;
//				//no use
//				PlayerSettings.shortBundleVersion = VersionEx.version_number.ToString();
//			}
//		}
//
//		if(EditorCommonTool.getPlatform() != Platform.ios)
//		{
////			string bundleIdentifier = "com.topgamesinc.evony" + SwitchConfig.compileType;
////			switch(SwitchConfig.compileType)
////			{
//////				case CompileType.alpha:
//////				{
//////					bundleIdentifier = "com.topgames.evonyalpha";
//////				}
//////				break;
////	
////				case CompileType.release:
////				{
////					bundleIdentifier = "com.topgamesinc.evonyrc";
////				}
////				break;
////			}
//
////			PlayerSettings.bundleIdentifier = bundleIdentifier;
////			PlayerSettings.iPhoneBundleIdentifier = bundleIdentifier;
//
//			string productName = "Evony";
//			//		if(SwitchConfig.compileType != CompileType.release)
//			{
//				PlayerSettings.productName = productName + "_" + SwitchConfig.compileType;
//			}
//			//		else
//			//		{
//			//			PlayerSettings.productName = "Evony(Beta)";
//			//		}
//		}
//	
//		AssetDatabase.SaveAssets();
//		AssetDatabase.Refresh();
//
//		
////		string filePath = "ProjectSettings/ProjectSettings.asset";
////		string str = CommonUtil.fileToString(filePath);
////		switch(EditorUserBuildSettings.activeBuildTarget)
////		{
////			case EditorCommonTool.build_target_ios:
////			{
////			str = Regex.Replace(str, "(\\s+iPhoneShortBundleVersion:\\s*)(.*)", "${1}" + Version.version);
////			str = Regex.Replace(str, "(\\s+iPhoneBundleVersion:\\s*)(.*)", "${1}" + Version.build_version);
////				//no use
////			str = Regex.Replace(str, "(\\s+AndroidBundleVersionCode:\\s*)(.*)", "${1}" + Version.build_version);
////			}
////			break;
////
////			case BuildTarget.Android:
////			{
////				str = Regex.Replace(str, "(\\s+iPhoneBundleVersion:\\s*)(.*)", "${1}" + Version.version);
////				str = Regex.Replace(str, "(\\s+AndroidBundleVersionCode:\\s*)(.*)", "${1}" + Version.build_version);
////				//no use
////				str = Regex.Replace(str, "(\\s+iPhoneShortBundleVersion:\\s*)(.*)", "${1}" + Version.build_version);
////			}
////			break;
////		}
////
////		bool ret = CommonUtil.stringToFile(str, filePath);
////		if(!ret)
////		{
////			Debug.LogError("fileToString Failed: " + filePath);
////		}
//	}
//
//	[MenuItem("Custom/OldProject/Version/TestVersion")]
//	public static void TestVersion()
//	{
//		string bundleVersion = PlayerSettings.bundleVersion;
//		string shortBundleVersion = PlayerSettings.shortBundleVersion;
//		int versionCode = PlayerSettings.Android.bundleVersionCode;
//		
//		Debug.Log(bundleVersion + " | " + shortBundleVersion + " | " + versionCode);
//		Debug.Log(PlayerSettings.applicationIdentifier + " | " + PlayerSettings.iPhoneBundleIdentifier);
//	}
////
////	[MenuItem("Custom/OldProject/Version/SwitchConfigAlpha")]
////	public static void SwitchConfigAlpha()
////	{
////		SetSwitchConfig(CompileType.alpha);
////	}
////
////	public static string replaceParam(string str, string paramName, string paramValue)
////	{
////		str = Regex.Replace(str, "(\\s+" + paramName + "\\s*=\\s*)(.*)", "${1}" + paramValue + ";");
////		return str;
////	}
////
////	public static void SetSwitchConfig(CompileType type)
////	{
////		string filePath = "Assets/Scripts/SwitchConfig.cs";
////		string str = CommonUtil.fileToString(filePath);
////
////		{
////			string paramName = "compileType";
////			string paramValue = "CompileType." + type.ToString();
////			str = replaceParam(str, paramName, paramValue);
////		}
////		bool ret = CommonUtil.stringToFile(str, filePath);
////		if(!ret)
////		{
////			Debug.LogError("fileToString Failed: " + filePath);
////		}
////	}
//}
//
//#endif